package com.zjy.business.system.manager.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjy.business.system.dao.SysConfigDao;
import com.zjy.business.system.domain.entity.SysConfig;
import com.zjy.business.system.domain.manager.query.ManagerListPageSysConfigQuery;
import com.zjy.business.system.manager.service.ManagerSysConfigService;
import com.zjy.web.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author yxb
 * create_time: 2024-10-24 10:27
 * description: 
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ManagerSysConfigServiceImpl implements ManagerSysConfigService {

    final private SysConfigDao sysConfigDao;

    @Override
    public void saveOrUpdate(SysConfig sysConfig) {
        // 校验参数
        checkSaveOrUpdateForm(sysConfig);
        Long id = sysConfig.getId();
        if (Objects.isNull(id)) {
            sysConfigDao.save(sysConfig);
        } else {
            sysConfigDao.updateByIdUpdateCache(sysConfig, SysConfig::getIdentification, sysConfig.getIdentification());
        }
    }

    /**
     * 校验参数
     * @param sysConfig
     */
    private void checkSaveOrUpdateForm(SysConfig sysConfig) {
        sysConfigDao.lambdaQuery()
                .eq(SysConfig::getIdentification, sysConfig.getIdentification())
                .ne(Objects.nonNull(sysConfig.getId()), SysConfig::getId, sysConfig.getId())
                .oneOpt().ifPresent(item -> {
                    throw BusinessException.EXCEPTION("已存在相同标识");
                });
    }

    @Override
    public void remove(Long id) {
        SysConfig sysConfig = sysConfigDao.getById(id);
        sysConfigDao.removeByIdDeleteCache(id, SysConfig::getIdentification, sysConfig.getIdentification());
    }

    @Override
    public PageInfo<SysConfig> listPageSysConfig(ManagerListPageSysConfigQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return sysConfigDao.listPageSysConfig(query);
    }

}
